<template>
  <view class="normal-login-container">
    <view class="logo-content">
      <image :src="logo" class="logo" mode="widthFix"></image>
      <view class="back_box">
        <image :src="backImg" mode="widthFix"></image>
      </view>
      <button v-if="privacyFlag" open-type="getPhoneNumber|agreePrivacyAuthorization"
        @getphonenumber="handleGetPhoneNumber" size="default"
        @agreeprivacyauthorization="handleAgreePrivacyAuthorization" class="login-btn block bg-gradual-green lg">
        授权手机号登录
      </button>

      <button open-type="getPhoneNumber" v-else @getphonenumber="handleGetPhoneNumber"
        class="login-btn block bg-gradual-green lg">
        授权手机号登录
      </button>

      <view class="read">
        <!-- <checkbox-group @change="handleChange" v-model="agree">
					<checkbox :value="1" :checked="checkedFlag" color="#D22C2C" backgroundColor="#409EFE"></checkbox>
				</checkbox-group> -->
        <view class="read-box" @click="handleChange">
          <image v-if="agree" :src="checkImg" style="width: 30rpx; height: 30rpx"></image>
          <image v-else :src="uncheckImg" style="width: 30rpx; height: 30rpx"></image>
        </view>
        我已阅读并同意
        <label class="agree-box" @click="showAgreeBox">《隐私及用户协议》</label>
      </view>
    </view>
    <!-- 选中 -->
    <view class="xieyi text-center">
      <text class="text-grey1">为了方便您能及时获取到消息通知，请及时关注</text>
      <text @click="handleUserAgrement" class="text-blue">"神煤交易智慧计量"</text>
      <text class="text-grey1">公众号,避免遗漏重要消息！</text>
    </view>
    <uni-popup class="tanantPop" type="dialog" ref="tenantDialog">
      <view class="tenantList">
        <text class="title">请选择要登录的租户：</text>
        <view class="tenant-box">
          <view v-for="(item, index) in tenantList" :key="index" class="tenant-item" @click="handleItem(item)">
            <text class="cph">{{ item.enterName }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
    <agreement v-if="privacyShow" ref="privacyBox" @handleAgree="handleAgreeFun"></agreement>
  </view>
</template>
<script>
  import {
    getPhoneByPhoneCode,
    getTenentList,
    wxPhoneLogin,
    getOpenIdByCode
  } from '@/api/login.js';
  import {
    getTenantId,
    setTenantId,
    setToken,
    setDriverId,
    setOpenId
  } from '@/utils/auth';
  import { toast } from '@/utils/common';
  import func from '@/utils/funlogin.js';
  import { getDriving } from '@/api/me.js';
  import config from '@/config';
  export default {
    name: 'Login',
    data() {
      return {
        agree: false,
        ysjhData: '',
        tenantid: '',
        phone_iv: '',
        session_key: '',
        phoneNumber: '',
        checkedFlag: false,
        privacyShow: true,
        privacyFlag: true,
        phone_encryptedData: '',
        globalConfig: getApp().globalData.config,
        wsLoginForm: {
          code: ''
        },
        tenantList: [],
        index: '',
        type: '',
        logo: config.baseImgUrl + '/logo.png',
        backImg: config.baseImgUrl + '/logo_back.png'
      };
    },
    onLoad(options) {
      this.$refs['tenantDialog'].close();
      this.type = options.type;
      if (wx.getPrivacySetting) {
        this.privacyFlag = true;
      } else {
        this.privacyFlag = false;
      }
    },
    computed: {
      curColor() {
        return this.$store.state.user.curTypeColor;
      },
      checkImg() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/checked1.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/checked.png';
        } else {
          return config.baseImgUrl + '/checked.png';
        }
      },
      uncheckImg() {
        return config.baseImgUrl + '/unchecked.png';
      }
    },
    methods: {
      handleAgreeFun(data) {
        this.agree = data == 1 ? true : false
      },
      showAgreeBox() {
        wx.openPrivacyContract({
          success: (res) => {
            console.log('openPrivacyContract success');
          },
          fail: (res) => {
            console.error('openPrivacyContract fail', res);
          }
        });
      },
      handleItem(e) {
        setTenantId(e.id);
        this.loginWx();
      },
      handleChange() {
        this.agree = !this.agree;
        if (this.agree) {
          this.$refs.privacyBox.agreeClick(this.agree);
        }
      },
      async loginWx() {
        //获取wx code
        const code = await func.wxLogin();
        const openid = await getOpenIdByCode(code);
        setOpenId(openid.data);
        const code1 = await func.wxLogin();
        const res = await wxPhoneLogin({ phoneCode: this.phoneNumber, loginCode: code1 })
        if (res.code == 0) {
          setToken({
            accessToken: res.data.accessToken,
            refreshToken: res.data.refreshToken
          });
          setDriverId(res.data.userId);
          this.getUserInfor();
        }
      },
      async loginWxByCode() {
        //获取wx code
        let code = await func.wxLogin();
        let data = {
          phoneCode: this.phoneNumber,
          loginCode: code
        };
        wxPhoneLogin(data).then((res) => {
          if (res.code == 0) {
            setToken({
              accessToken: res.data.accessToken,
              refreshToken: res.data.refreshToken
            });
            setDriverId(res.data.userId);
            this.getUserInfor();
          }
        });
      },
      //获取司机用户信息
      async getUserInfor() {
        try {
          let res = await getDriving();
          if (res.code == 0) {
            if (res.data?.isIdIdentified) {
              uni.setStorageSync('sjxxData', res.data);
              if (this.type === 'code') {
                if (uni.getStorageSync('isSetSjxx') === 'net') {
                  this.$tab.reLaunch('/pages/receivingNet?codes=true');
                } else if (uni.getStorageSync('isSetSjxx') === 'bj') {
                  this.$tab.reLaunch('/pages/receivingBJ?codes=true');
                } else if (uni.getStorageSync('isSetSjxx') === 'jy') {
                  this.$tab.reLaunch('/pages/receivingJY?codes=true');
                } else if (uni.getStorageSync('isSetSjxx') === 'jl') {
                  this.$tab.reLaunch('/pages/receiving?codes=true');
                }
              } else {
                this.removeStorage()
                this.$tab.reLaunch('/pages/goodsSource');
              }
            } else {
              // 身份实名没有认证
              if (this.type === 'code') {
                uni.navigateTo({
                  url: '/packageB/pages/mine/driver-auth/driver-auth?type=code'
                });
              } else {
                this.removeStorage()
                this.$tab.reLaunch('/packageB/pages/mine/driver-auth/driver-auth');
              }
            }
          } else {
            this.$tab.reLaunch('/pages/login');
          }
        } catch (e) {
          return false;
        }
      },
      handleAgreePrivacyAuthorization(ee) { },
      async handleGetPhoneNumber(e) {
        let _ = this;
        console.log(_.agree, '这是勾选的值');
        if (!_.agree) {
          // 未勾选协议
          toast('请勾选用户隐私协议');
          return;
        }
        _.errMsg = e.detail.errMsg;
        console.log('e.detail.code:', e.detail.code);

        const res = await getPhoneByPhoneCode(e.detail.code);
        if (res.code == 0) {
          _.phoneNumber = res.data;
        }
        if (!!getTenantId()) {
          _.loginWxByCode();
          return;
        }
        //获取租户列表  tenantList
        const res1 = await getTenentList(_.phoneNumber);
        if (res1.code == 0) {
          if (res1.data.length == 0) {
            uni.showToast({
              title: '未找到接单企业，请通过二维码或接单页面进入',
              icon: 'none'
            });
            return;
          }
          _.tenantList = res1.data;
          if (res1.data.length == 1) {
            //直接用
            setTenantId(res1.data[0].id);
            _.loginWx();
          } else {
            //跳转到租户下拉选择页面
            _.$refs['tenantDialog'].open('bottom');
          }
        }
        // if(!_this.agree){
        // 	return
        // }
        // wx.showModal({
        //   title: '请求授权',
        //   content: '为了提供更完善的服务，我们需要获取您的手机号用于后续联系。您可以选择不授权，但可能无法正常使用某些功能。',
        //   success (res) {
        //     if (res.confirm) {
        //       // 用户点击确定
        // 	  wx.login({
        //         async success (e) {
        //           console.log('获取手机号成功456: ', e)
        //         },
        //         fail (err) {
        //           console.log('获取手机号失败789: ', err)
        //         }
        //       })

        //       // wx.getPhoneNumber({
        //       //   success (res) {
        //       //     console.log('获取手机号成功: ', res.phoneNumber)
        //       //   },
        //       //   fail (err) {
        //       //     console.log('获取手机号失败: ', err)
        //       //   }
        //       // })
        //     } else if (res.cancel) {
        //       // 用户点击取消
        //       console.log('用户取消授权')
        // 	  return
        //     }
        //   }
        // })

        // if (e.detail.errMsg == 'getPhoneNumber:ok') {
        // this.errMsg = e.detail.errMsg;
        // this.phone_encryptedData = e.detail.encryptedData;
        // this.phone_iv = e.detail.iv;

        // 获取手机号
        // console.log('手机号123:', e);

        // }
        // this.updateToken(obj.memberToken) 存token
      },
      // 跳转公众号
      handleUserAgrement() {
        let site = this.globalConfig.appInfo.agreements[1];
        this.$tab.navigateTo(
          `/pages/common/webview/index?title=${site.title}&url=${site.url}`
        );
      },
      removeStorage() {
        uni.removeStorageSync('scanData');
        uni.removeStorageSync('ysjhData');
        uni.removeStorageSync('isSetSjxx');
      }
    }
  };
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }

  .checkbox input[type='checkbox']+.checkbox__input::after {

    /* 通过deep或>>>来穿透scoped */
    ::v-deep .checkbox input[type='checkbox']+.checkbox__input::after,
    .checkbox input[type='checkbox']+.checkbox__input::after {
      border-color: #409efe;
      background-color: #409efe;
    }
  }

  .privacyBox {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 710rpx;
    height: 510rpx;
    margin-left: -355rpx;
    background: #f5f5f5;
    margin-top: -255rpx;
    border-radius: 5px;
    padding: 60rpx;
    box-sizing: border-box;
  }

  .privacyTit {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    overflow: hidden;
  }

  .privacyDesc {
    font-size: 28rpx;
    color: #333;
    overflow: hidden;
    margin-top: 30rpx;
  }

  .privacyDesc text {
    color: #333;
  }

  .privacyPost {
    overflow: hidden;
    margin-top: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .privacyPost .refuseBtn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #fff;
    background: #333;
    border-radius: 40rpx;
    box-sizing: border-box;
    overflow: hidden;
  }

  .privacyPost .agreeBtn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #fff;
    background: blue;
    border-radius: 40rpx;
    box-sizing: border-box;
    overflow: hidden;
    margin-left: 20rpx;
  }

  .tenantList {
    z-index: 99999;
    background: #fff;
    font-size: 14px;
    padding: 30px 10px 35px 10px;
    margin: 15px;
    border-radius: 5px;

    .tenant-box {
      max-height: 533.33rpx;
      overflow-y: auto;
    }

    .title {
      margin-bottom: 36rpx;
      display: block;
    }

    .tenant-item {
      text-align: center;
      height: 40px;
      line-height: 40px;
      border-radius: 5px;
      background: #d9d9d952;
      margin-bottom: 3rpx;
      color: #666;
      cursor: pointer;
      padding: 6rpx 0;
      margin-top: 10px;
    }

    .tenant-item:hover {
      background: #ececec;
    }
  }

  .agrementList {
    margin: 15px;
    border-radius: 5px;

    .title {
      text-align: center;
      font-weight: bold;
    }
  }

  .normal-login-container {
    width: 100%;
    height: 100vh;
    background: #f5f5f5;

    .logo-content {
      width: 95%;
      font-size: 20rpx;
      text-align: center;
      margin: 2%;
      background: #fff;
      padding: 3%;

      image {
        border-radius: 4rpx;
        width: 375pt;
        height: auto;
      }

      image.logo {
        border-radius: 4rpx;
        margin-top: 41px;
        width: 65pt;
      }

      .back_box {
        margin-bottom: 50pt;
      }
    }

    .login-form-content {
      text-align: center;

      width: 100%;

      .input-item {
        margin: 20px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }
      }

      .login-btn {
        margin-bottom: 40rpx;
        height: 90rpx;
      }
    }

    .read {
      margin-bottom: 40rpx;
      padding: 20rpx 0;
      text-align: left;
      font-size: 14px;
      margin-left: 2rpx;
      position: relative;

      checkbox {
        transform: scale(0.7);
        text-indent: 10px;
      }

      .text-box {
        position: absolute;
        top: 13px;
        left: 37px;
        width: 260px;
        font-size: 28rpx;
      }

      .agree-box {
        position: absolute;
        top: 22rpx;
      }
    }

    .xieyi {
      color: #333;
      font-size: 24rpx;
      padding: 20rpx;
    }
  }

  .login-code-img {
    height: 45px;
  }
</style>